using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.UI;
using System.Linq;

public class Manager : MonoBehaviour
{
    public Menu menu;
    public DisplayArea displayArea;
    public SyncArea syncArea;
    public PathSettingWindow pathSettingWindow;
    public PathSettingWIndow_IFS pathSettingWIndow_IFS;
    public GameObject errorArea;
    public ComfirmWindow comfirmWindow;

    [SerializeField] Text logText;
    [SerializeField] ScrollRect logScroll;

    public bool isReady = false;
    public string rootPath;
    public string originPath;
    public string serverPath;
    public string clientPath;
    public string mappingPath;
    public string languagePath;
    public string temp1Path { get { return Path.Combine(Application.streamingAssetsPath, "temp1"); } }
    
    [HideInInspector] public Dictionary<string, stFile> files = new Dictionary<string, stFile>();
    [HideInInspector] public List<ExcelEample> excelEamples = new List<ExcelEample>();

    bool inited = false;

    void Start()
    {
        Tools.manager = this;
        Tools.logText = logText;
        Tools.logScroll = logScroll;

        if(!CheckSvnExist())
        {
            errorArea.SetActive(true);
            return;
        }

        if(pathSettingWindow.Init())
        {
            Init();
            RefreshFiles();
        }
    }

    public void Init()
    {
        isReady = true;
        Tools.Log("加载版本：" + PlayerPrefs.GetString("CurtVersion:"));
        LoadExcelsByMapping();
        LanguageTools.Init(this);
        LanguageTools.ReloadLanguage();
        displayArea.Init();
        syncArea.Init();
        inited = true;
    }

    void OnApplicationFocus(bool hasFocus)
    {
        if (hasFocus)
        {
            RefreshFiles();
        }
    }

    bool CheckSvnExist()
    {
        try
        {
            Tools.ExecuteSvnCommand("--version", false);
        }
        catch(System.Exception e)
        {
            Debug.Log(e);
            return false;
        }

        return true;
    }

    // 加载对照表
    void LoadExcelsByMapping()
    {
        files.Clear();
        using (StreamReader reader = new StreamReader(mappingPath, Encoding.GetEncoding("GB2312")))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] columns = line.Split(',');
                stFile file = new stFile
                {
                    excelName = columns[0],
                    simpleName = columns[0].Replace("《破天一剑》", ""),
                    csvName = columns[1],
                    excelFullPath = Path.Combine(originPath, columns[0] + ".xlsx"),
                    serverFullPath = Path.Combine(serverPath, columns[1] + ".csv"),
                    cliectFullPath = Path.Combine(clientPath, columns[1] + ".csv"),
                    state = emFileState.Normal
                };
                files.Add(columns[0], file);
            }
        }

        Tools.Log($"读取到 {files.Count} 个文件");
    }

    public void TriggerAllFileState()
    {
        for (int i = 0; i < excelEamples.Count; i++)
        {
            excelEamples[i].RefreshStateBySVN(excelEamples[i].me);
        }
    }

    public string GB2312ToUTF8(string str)
    {
        byte[] gb2312Bytes = Encoding.GetEncoding("GB2312").GetBytes(str); // 将 GB2312 编码的字符串转换为字节数组
        string utf8String = Encoding.UTF8.GetString(gb2312Bytes); // 将字节数组使用 UTF-8 编码转换为字符串
        return utf8String;
    }

    public void DeleteDirectory(string folderPath)
    {
        // 确保文件夹存在
        if (Directory.Exists(folderPath))
        {
            // 删除文件夹里的所有文件
            string[] files = Directory.GetFiles(folderPath);
            foreach (string file in files)
            {
                File.Delete(file);
            }

            // 删除文件夹本身
            Directory.Delete(folderPath);
        }
    }

    public async void OnUpdateButton()
    {
        await Tools.ExecuteSvnCommandAsync($"update {rootPath}");
    }

    public async void OnCleanButton()
    {
        await Tools.ExecuteSvnCommandAsync($"cleanup {rootPath}");
    }

    public void RefreshFiles()
    {
        if(!inited) return;

        // 重新加载多语言对照表
        if(LanguageTools.IsChanged())
        {
            LanguageTools.ReloadLanguage();
        }

        // 重置所有文件状态
        foreach (var key in files.Keys.ToList())
        {
            files[key].state = emFileState.Normal;
        }

        // 从SVN获取数据
        string output = Tools.ExecuteSvnCommand("status " + originPath);

        // 提取修改过的文件
        List<string> excel = new List<string>();
        string[] lines = output.Split('\n');
        foreach (var line in lines)
        {
            string[] columns = line.Split("       ");
            if(columns.Length >= 2)
            {
                string excelName = Path.GetFileNameWithoutExtension(columns[1].Trim());
                switch(columns[0])
                {
                    case "M":
                        if(files.ContainsKey(excelName))
                        {
                            files[excelName].state = emFileState.Modify;
                        }
                        break;
                    case "C":
                        if(files.ContainsKey(excelName))
                        {
                            files[excelName].state = emFileState.Conflict;
                        }
                        break;
                }
            }
        }

        TriggerAllFileState();
        syncArea.RefreshModifyScroll();
    }
}
